import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api'

const actions = {
    // 获取购物车列表
    async getCartList({ commit }) {
        let result = await reqCartList();
        if (result.code == 200) {
            commit('GETCARTLIST', result.data)
        }
    },
    // 删除购物车产品
    async deleteCartBySkuId({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    // 改变选中状态
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    // 删除勾选产品
    // deleteChecked(context){
    //     // context：小仓库、commit（提交mutations修改state）、getters（计算属性）、dispatch
    //     context.dispatch()
    // }
    deleteChecked({ dispatch, getters }) {
        let promiseArr = [];
        getters.cartList.cartInfoList.forEach(item => {
            // dispatch 返回一个promise
            let promise = item.isChecked == 1 ? dispatch('deleteCartBySkuId', item.skuId) : ''
            promiseArr.push(promise)
        })
        return Promise.all(promiseArr);
    },
    // 修改全选
    updateCheckedAll({ dispatch, state }, isChecked) {
        let promiseArr = [];
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked })
            promiseArr.push(promise)
        })
        return Promise.all(promiseArr);
    },
}

const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList;
    }
};

const state = {
    cartList: [],
};

const getters = {
    cartList(state) {
        return state.cartList[0] || {}
    },
    // cartInfoList(state){
    //     return state.
    // }
};

export default {
    state,
    mutations,
    actions,
    getters,
};